/*
 * ReminderView.java
 *
 * Created on December 10, 2008, 11:41 AM
 */

package researchgrants.parts.GrantRequest.reminder;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import researchgrants.parts.GrantRequest.GrantRequest;
import researchgrants.parts.GrantRequest.statusChanges.GrantRequestStatusChange;
import researchgrants.parts.GrantRequest.statusChanges.GrantRequestStatusChangeSubmitted;
import researchgrants.parts.LoggedData.LoggedData;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsDate;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsTextArea;
import researchgrants.parts.date.DateForDb;
import researchgrants.parts.db.Db;
import researchgrants.parts.panelsManager.LoggedDataPanelsManager;
import researchgrants.utils.MyDialog;

/**
 *
 * @author  DOStudent1
 */
public class ReminderView extends MyDialog {

    private static final int hgap=0;
    private Reminder reminder;
    private boolean isNew;
    private GrantRequest grantRequest;
            
    private LoggedDataPanelsManager dateView;
    private LoggedDataPanelsManager notesView;
    private LoggedDataPanelsDate loggedDataPanelsDate;

    private JButton btnSaveAll;
    private JPanel pnlWarnings=new JPanel();
    
    //inputs a new reminder
    ReminderView(Window parent, GrantRequest grantRequest) {
        super(parent);
        isNew=true;
        this.grantRequest=grantRequest;
        initComponents();
        initDisplay();
    }

    //shows an existing reminder
    ReminderView(Window parent, Reminder reminder) {
        super(parent);
        this.reminder=reminder;
        isNew=false;
        initComponents();
        initDisplay();
    }
   
    private void createNewFromFields() {
        try {

            Connection conn=Db.openDbConnection();
            PreparedStatement createStatement = Db.createPreparedStatement(conn, "INSERT INTO tblReminders (DateRef, NotesRef) VALUES (?, ?)");

            
            ////////////////////////////////////
            // Save all different data pieces
            ////////////////////////////////////
            
            createStatement.setInt(1, saveLoggedDataPanelsManagerData(dateView));
            createStatement.setInt(2, saveLoggedDataPanelsManagerData(notesView));

            
            createStatement.executeUpdate();

            int newId = Db.getLastIdentity();
            createStatement.close();
            Db.closeDbConnection(conn);
            
            this.reminder=Reminder.getById(newId);
            
            //setVisible(false);
            
        } catch (SQLException ex) {
            Logger.getLogger(ReminderView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
//        isNew=false;
//        initDisplay();
        setVisible(false);
    }
    
    private void initDisplay() {
        if (isNew) {
            btnSaveAll=new JButton("Save New Reminder");
            btnSaveAll.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    createNewFromFields();
                }

            });
        }

        
        if (isNew) {
            lblId.setText("<Auto>");
        } else {
            lblId.setText(Integer.toString(reminder.getId()));
        }

        
        LoggedData date=null;
        LoggedData notes=null;
        
        if (!isNew) {
            date=reminder.getLoggedDataDate();
            notes=reminder.getLoggedDataNotes();
        }
        
        
        ///////////////////////////////////////
        // adds all the internal data's views
        ///////////////////////////////////////
        
        loggedDataPanelsDate=new LoggedDataPanelsDate();
        dateView=createLoggedDataPanelManager(true, isNew, loggedDataPanelsDate, this, date, pnlFieldDate, new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                validateDate();
            }
        });
        LoggedDataPanelsTextArea loggedDataPanelsNotes=new LoggedDataPanelsTextArea();
        notesView=createLoggedDataPanelManager(false, isNew, loggedDataPanelsNotes, this, notes, pnlFieldNotes);


        /////////////////////////////////////////////////////////////////////
        // Sets the default values for fields, if inputing a new Reminder
        /////////////////////////////////////////////////////////////////////
        
        if (isNew) {
            Date reminderDate=null;
            String reminderNotes="";
            
            GrantRequestStatusChange lastStatusChange = grantRequest.getLastStatusChange();
            
            if (lastStatusChange==null) {
                // A new GrantRequest - use the deadline
                Date deadline=grantRequest.getCurrentDeadline();
                if (deadline!=null) {
                    reminderDate=oneWeekBefore(deadline);
                    reminderNotes="A week before the deadline";
                } else {
                    reminderNotes="Before the deadline";
                }
            } else {
                if (lastStatusChange instanceof GrantRequestStatusChangeSubmitted) {
                    // A submitted GrantRequest - use the expected decision
                    Date expectedDecisionDate=((GrantRequestStatusChangeSubmitted)lastStatusChange).getCurrentExpectedDecisionDate();
                    if (expectedDecisionDate!=null) {
                        reminderDate=oneWeekBefore(expectedDecisionDate);
                        reminderNotes="A week before the expected decision";
                    } else {
                        reminderNotes="Before the expected decision";
                    }
                } 
            }
            
            loggedDataPanelsNotes.setDefaultValue(reminderNotes);
            notesView.display();
            if (reminderDate!=null) {
                loggedDataPanelsDate.setDefaultValue(DateForDb.fromDate(reminderDate).toDbString());
                dateView.display();
            }
        }
        
        
        JPanel pnlOptionalButtonsInner=new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        pnlOptionalButtonsInner.setLayout(new GridLayout());
        
        boolean displayButtonsPanel=false;
        // only if the Reminder is new, allow to save the initial data
        if (isNew) {
            JPanel pnlOptionalButtonsInner2=new JPanel(new BorderLayout(0, 0));
            pnlOptionalButtonsInner2.add(pnlWarnings, BorderLayout.NORTH);
            pnlOptionalButtonsInner2.add(btnSaveAll, BorderLayout.CENTER);
            pnlOptionalButtonsInner.add(pnlOptionalButtonsInner2);
            displayButtonsPanel=true;
        }
        
        pnlOptionalButtons.removeAll();
        // if no buttons, remove panel
        if (displayButtonsPanel) {
                pnlOptionalButtons.add(wrapSection(pnlOptionalButtonsInner, "Options"));
        }
        
        pack();
        setLocationRelativeTo(getParent());
        setVisible(true);

    }

    
    public Reminder getReminder() {
        return(reminder);
    }

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pnlID = new javax.swing.JPanel();
        lblCaptionId = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        pnlDate = new javax.swing.JPanel();
        lblCaptionDate = new javax.swing.JLabel();
        pnlFieldDate = new javax.swing.JPanel();
        pnlNotes = new javax.swing.JPanel();
        pnlNotes2 = new javax.swing.JPanel();
        lblCaptionNotes = new javax.swing.JLabel();
        pnlFieldNotes = new javax.swing.JPanel();
        pnlOptionalButtons = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(researchgrants.ResearchGrantsApp.class).getContext().getResourceMap(ReminderView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        pnlID.setName("pnlID"); // NOI18N
        pnlID.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionId.setText(resourceMap.getString("lblCaptionId.text")); // NOI18N
        lblCaptionId.setName("lblCaptionId"); // NOI18N
        pnlID.add(lblCaptionId);

        lblId.setName("lblId"); // NOI18N
        pnlID.add(lblId);

        getContentPane().add(pnlID);

        pnlDate.setName("pnlDate"); // NOI18N
        pnlDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionDate.setText(resourceMap.getString("lblCaptionDate.text")); // NOI18N
        lblCaptionDate.setName("lblCaptionDate"); // NOI18N
        pnlDate.add(lblCaptionDate);

        pnlFieldDate.setName("pnlFieldDate"); // NOI18N
        pnlFieldDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlDate.add(pnlFieldDate);

        getContentPane().add(pnlDate);

        pnlNotes.setName("pnlNotes"); // NOI18N
        pnlNotes.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        pnlNotes2.setName("pnlNotes2"); // NOI18N
        pnlNotes2.setLayout(new java.awt.GridBagLayout());

        lblCaptionNotes.setText(resourceMap.getString("lblCaptionNotes.text")); // NOI18N
        lblCaptionNotes.setName("lblCaptionNotes"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
        pnlNotes2.add(lblCaptionNotes, gridBagConstraints);

        pnlFieldNotes.setName("pnlFieldNotes"); // NOI18N
        pnlFieldNotes.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        pnlNotes2.add(pnlFieldNotes, gridBagConstraints);

        pnlNotes.add(pnlNotes2);

        getContentPane().add(pnlNotes);

        pnlOptionalButtons.setName("pnlOptionalButtons"); // NOI18N
        pnlOptionalButtons.setLayout(new javax.swing.BoxLayout(pnlOptionalButtons, javax.swing.BoxLayout.LINE_AXIS));
        getContentPane().add(pnlOptionalButtons);

        pack();
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblCaptionDate;
    private javax.swing.JLabel lblCaptionId;
    private javax.swing.JLabel lblCaptionNotes;
    private javax.swing.JLabel lblId;
    private javax.swing.JPanel pnlDate;
    private javax.swing.JPanel pnlFieldDate;
    private javax.swing.JPanel pnlFieldNotes;
    private javax.swing.JPanel pnlID;
    private javax.swing.JPanel pnlNotes;
    private javax.swing.JPanel pnlNotes2;
    private javax.swing.JPanel pnlOptionalButtons;
    // End of variables declaration//GEN-END:variables

    private boolean isDateValid=false;

    /**
     * Issued after a change to the date field.
     * Used for validating the entire form, so that no one can save it with invalid parts
     */
    private void validateDate() {
        isDateValid=loggedDataPanelsDate.isValid() && (!loggedDataPanelsDate.isEmpty());
        validateEntireForm();
    }

    
    private void validateEntireForm() {
        setSaveEnabled(isDateValid);
        pnlWarnings.removeAll();
        int warnings=0;
        if (!isDateValid) {
            JLabel lblWarning=new JLabel("You must select a valid date");
            lblWarning.setForeground(Color.RED);
            pnlWarnings.add(lblWarning);
            warnings++;
        }

        pnlWarnings.setLayout(new GridLayout(warnings, 1));
        pnlWarnings.revalidate();
    }
    
    private void setSaveEnabled(boolean enabled) {
        // will only be used when a global save button is availalbe
        if (btnSaveAll!=null) {
            btnSaveAll.setEnabled(enabled);
        }
    }
    
    /**
     * Returns a new date of one week before the given date.
     * Use to give extra time before deadlines.
     * @param date the date to relate to
     * @return a date one week before the given one
     */
    private static Date oneWeekBefore(Date date) {
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.WEEK_OF_YEAR, -1);
        return(calendar.getTime());
    }

    
    
}
